#include "ICECamera.h"
#include "ice_ipcsdk.h"

static int ICECameraObj = 0;

void CALLBACK ICEANPRInfoCallback(void *pvParam, const ICE_CHAR *pcIP, const ICE_CHAR *pcNumber, const ICE_CHAR *pcColor,
    ICE_CHAR *pcPicData, ICE_U32 u32PicLen, ICE_CHAR *pcCloseUpPicData, ICE_U32 u32CloseUpPicLen,
    ICE_S16 s16Speed, ICE_S16 s16VehicleType, ICE_S16 s16Reserved1, ICE_S16 s16Reserved2,
    ICE_FLOAT fPlateConfidence, ICE_U32 u32VehicleColor, ICE_U32 u32PlateType, ICE_U32 u32VehicleDir,
    ICE_U32 u32AlarmType, ICE_U32 u32SerialNum, ICE_U32 uCapTime, ICE_U32 u32ResultHigh, ICE_U32 u32ResultLow);

ICECamera::ICECamera(void)
{
    if (ICECameraObj == 0)
    {
        ICE_IPCSDK_Init();
    }

    ICECameraObj++;

    type = CAMERA_TYPE::ICE_CAMERA;
}

ICECamera::~ICECamera(void)
{
    ICECameraObj--;

    if (ICECameraObj == 0)
    {
        ICE_IPCSDK_Fini();
    }
}

int ICECamera::Init(HWND hwnd, const char *IPAddress, int port, const char *userName, const char *password, int channel, int stream)
{
    this->hwnd = hwnd;
    this->IPAddress = IPAddress;
    this->port = port;
    this->userName = userName;
    this->password = password;
    this->channel = channel;
    this->stream = stream;

    return this->handle;
}

int ICECamera::Connect()
{
    realPlayHandle = ICE_IPCSDK_OpenPreview(IPAddress.c_str(), 1, 1, (ICE_U32)hwnd, ICEANPRInfoCallback, this);

    if (realPlayHandle == 0)
    {
        return 1;
    }

    return 0;
}

int ICECamera::Disconnect()
{
    ICE_IPCSDK_Close(realPlayHandle);

    return 0;
}

void ICECamera::SetCallback(VideoDataCallback callback, void *context)
{
}

void ICECamera::SetANPRInfoCallback(ANPRInfoCallback callback, void *context)
{
    this->anprInfoCallback = callback;
    this->anprInfoCallbackContext = context;
}

void CALLBACK ICEANPRInfoCallback(void *pvParam, const ICE_CHAR *pcIP, const ICE_CHAR *pcNumber, const ICE_CHAR *pcColor,
    ICE_CHAR *pcPicData, ICE_U32 u32PicLen, ICE_CHAR *pcCloseUpPicData, ICE_U32 u32CloseUpPicLen,
    ICE_S16 s16Speed, ICE_S16 s16VehicleType, ICE_S16 s16Reserved1, ICE_S16 s16Reserved2,
    ICE_FLOAT fPlateConfidence, ICE_U32 u32VehicleColor, ICE_U32 u32PlateType, ICE_U32 u32VehicleDir,
    ICE_U32 u32AlarmType, ICE_U32 u32SerialNum, ICE_U32 uCapTime, ICE_U32 u32ResultHigh, ICE_U32 u32ResultLow)
{
    if (u32PicLen > 100)
    {
        ICECamera *camera = (ICECamera *)pvParam;

        FILE *imageFile = NULL;
        imageFile = fopen("temp.jpg", "wb");
        fwrite(pcPicData, u32PicLen, 1, imageFile);
        fclose(imageFile);
        IplImage *image = cvLoadImage("temp.jpg");
        DeleteFile("temp.jpg");

        if (camera->anprInfoCallback)
            camera->anprInfoCallback(camera->handle, pcNumber, (unsigned char*)image->imageData, image->imageSize, image->width, image->height, camera->anprInfoCallbackContext);

        cvReleaseImage(&image);
    }
}
